const WENXIN_API_KEY = 'bce-v3/ALTAK-qYhet353HjURUSqkkRupy/28caf787e8a587f8a721c9ef129b203d9e0399a4';
const WENXIN_ACCESS_KEY = 'ALTAKzC7utoVFZlPrxKGYevx7u';
// 使用代理路径访问 Wenxin API
const WENXIN_API_URL = '/wenxin/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions';

interface WenxinResponse {
  id: string;
  object: string;
  created: number;
  result: string;
  is_truncated: boolean;
  need_clear_history: boolean;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

export async function askWenxin(question: string, context: string = '') {
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', `Bearer ${WENXIN_API_KEY}`);
  headers.append('X-Access-Key', WENXIN_ACCESS_KEY);

  const body = JSON.stringify({
    messages: [
      {
        role: 'user',
        content: `你是一个专业的教学助手，请根据提供的教学内容回答学生的问题。\n\n教学内容：${context}\n\n学生问题：${question}`
      }
    ]
  });

  const response = await fetch(WENXIN_API_URL, {
    method: 'POST',
    headers: headers,
    body: body,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
  }

  return response.json() as Promise<WenxinResponse>;
}